#!/usr/bin/env python3
# Copyright 2022 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Pulls the latest revisions of the wpt tooling."""

import os
import subprocess
import sys

BUG_QUERY_URL = ("https://bugs.chromium.org/p/chromium/issues/list?"
                 "q=component%3ABlink%3EInfra%3EEcosystem%20%22WPT%20Tooling%20Roll%22&can=2")


def main():
    current_branch = subprocess.check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])
    print("Roll wpt on branch: %s" % current_branch.rstrip().decode('utf-8'))
    print("Are there outstanding bugs at %s (Y/n)?" % BUG_QUERY_URL,
          end='', flush=True)
    yesno = sys.stdin.read(1)
    if yesno not in ['N', 'n']:
        return 1

    remote_head = subprocess.check_output(['git',
                                           'ls-remote',
                                           'https://github.com/web-platform-tests/wpt',
                                           'refs/heads/master'])
    remote_head = remote_head.rstrip().decode('utf-8').split()
    remote_head = remote_head[0]
    print("Roll to remote head: %s" % remote_head)

    pattern = "s/^Version: .*$/Version: %s/g" % remote_head
    path_to_wpt_tools_dir = os.path.abspath(os.path.dirname(__file__))
    path_to_readme = os.path.join(path_to_wpt_tools_dir, "README.chromium")

    # Update Version in //third_party/wpt_tools/README.chromium
    # This program only works on linux for now, as sed has slightly
    # different format on mac
    print("Update commit hash code for %s" % path_to_readme)
    subprocess.check_call(["sed", "-i", pattern, path_to_readme])

    path_to_checkout = os.path.join(path_to_wpt_tools_dir, "checkout.sh")
    print("Call %s\n" % path_to_checkout)
    subprocess.check_output([path_to_checkout, remote_head])

    change_files = subprocess.check_output(['git',
                                            'diff',
                                            'HEAD',
                                            '--no-renames',
                                            '--name-only'])
    change_files = change_files.decode('utf-8').strip()
    if change_files == '':
        print("No changes to roll!")
        return 0

    subprocess.check_call(['git', 'add', path_to_wpt_tools_dir])
    wpt_try_bots = ["linux-wpt-identity-fyi-rel",
                    "linux-wpt-input-fyi-rel",
                    "android-weblayer-pie-x86-wpt-smoketest"]
    upstream_url = "https://github.com/web-platform-tests/wpt"
    message = "Roll wpt tooling\n\nThis rolls wpt to latest commit at\n%s.\n" % upstream_url
    message += "REMOTE-WPT-HEAD: %s\n\n" % remote_head
    message += "Cq-Include-Trybots: luci.chromium.try:%s\n" % ','.join(wpt_try_bots)
    subprocess.check_call(['git', 'commit', '-m', message])
    subprocess.check_call(['git',
                           'cl',
                           'upload',
                           '--cq-dry-run',
                           '--bypass-hooks',
                           '-f'])

    output = subprocess.check_output(['git', 'cl', 'issue']).decode('utf-8')
    issue_number = output.strip().split()[2]
    print("\nCL uploaded to https://chromium-review.googlesource.com/%s" % issue_number)
    print("Please monitor the results on WPT try bots.")
    print("One common failure is that some dependency is not satisfied.")
    print("Please consider update WPTIncludeList in such case.")
    return 0

if __name__ == '__main__':
    sys.exit(main())
